import {getParameterByName, myFetch} from './utils.js';
const env = process.env.NODE_ENV;
let userId, userInfo;


const getUserId = () => {
	if(env === 'development') 
		return Promise.resolve(200535);
	else return new Promise(res => {
		if(userId) res(userId);
		else {
			myFetch({
				name: 'shopping.sys.wxlogin',
				code: getParameterByName('code')
			}).then(data => {
				// alert(data)
				if(data.success) {
					userId = data.data.user_id;
					res(userId);
				} else {
					alert(location.href);
					location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx23fbcdfe606a66cc&redirect_uri=${location.href}&response_type=code&scope=snsapi_userinfo#wechat_redirect`);
				}
			})
		}
	})
}

const getUserInfo = () => {
	return new Promise(res => {
		if(userInfo) res(userInfo);
		else if(env === 'development') {
			myFetch({
				data:{
					name: 'shopping.sys.getInfoByOpenid',
					openid: 'oE7ThtytpqabZ_6VgsHMMvZfIF5I'
				}
			}).then(data => {
				userInfo = data.data;
				res(data.data)
			})
		}
		else {
			getUserId().then(id => {
				myFetch({
					name: 'shopping.sys.user.info',
					user_id: id
				}).then(data => {
					userInfo = data.data
					res(data.data)
				})
			})
		}
	})
}

const wxPayLogin = () => {
	return new Promise(res => {
		if(!getParameterByName('code')) 
			location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxca54e54a9155264a&redirect_uri=${location.href.slice(0,-2)}&response_type=code&scope=snsapi_base#wechat_redirect`);
		res(getParameterByName('code'));
	})
}

export {getUserInfo, wxPayLogin}